<template>
  <div class="iframe-container">
    <iframe
      ref="iframeRef"
      :src="src"
      width="100%"
      height="100%"
      frameborder="0"
      :name="name"
      @load="handleLoad"
      @error="handleError"
    />
    
    <div v-if="loading" class="iframe-loading">
      <el-icon class="is-loading" :size="40">
        <Loading />
      </el-icon>
      <p>{{ loadingText }}</p>
    </div>

    <div v-if="error" class="iframe-error">
      <el-icon :size="60">
        <WarningFilled />
      </el-icon>
      <h3>页面加载失败</h3>
      <p>{{ errorMessage }}</p>
      <el-button type="primary" @click="reload">重新加载</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { Loading, WarningFilled } from '@element-plus/icons-vue'

interface Props {
  src: string
  name?: string
  loadingText?: string
  autoHeight?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  name: 'iframe',
  loadingText: '页面加载中...',
  autoHeight: true
})

const iframeRef = ref<HTMLIFrameElement>()
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')

// 计算iframe源地址
const src = computed(() => {
  if (!props.src) return 'about:blank'
  
  // 如果是相对路径，转换为绝对路径
  if (props.src.startsWith('/')) {
    return window.location.origin + props.src
  }
  
  return props.src
})

// iframe加载完成
const handleLoad = () => {
  loading.value = false
  error.value = false
  
  if (props.autoHeight) {
    adjustHeight()
  }
}

// iframe加载错误
const handleError = () => {
  loading.value = false
  error.value = true
  errorMessage.value = '无法加载页面内容，请检查链接是否正确'
}

// 调整iframe高度
const adjustHeight = () => {
  if (!iframeRef.value) return
  
  try {
    const iframeDoc = iframeRef.value.contentDocument || iframeRef.value.contentWindow?.document
    if (iframeDoc) {
      const body = iframeDoc.body
      const html = iframeDoc.documentElement
      
      const height = Math.max(
        body?.scrollHeight || 0,
        body?.offsetHeight || 0,
        html?.scrollHeight || 0,
        html?.offsetHeight || 0
      )
      
      if (height > 0) {
        iframeRef.value.style.height = height + 'px'
      }
    }
  } catch (err) {
    // 跨域时无法访问iframe内容，保持默认高度
    console.warn('Cannot access iframe content due to cross-origin restrictions:', err)
  }
}

// 重新加载
const reload = () => {
  if (iframeRef.value) {
    loading.value = true
    error.value = false
    iframeRef.value.src = src.value
  }
}

// 监听src变化
watch(() => props.src, () => {
  if (props.src) {
    loading.value = true
    error.value = false
  }
})

let heightTimer: number

onMounted(() => {
  // 定时调整高度（仅对同源iframe有效）
  if (props.autoHeight) {
    heightTimer = window.setInterval(adjustHeight, 2000)
  }
})

onUnmounted(() => {
  if (heightTimer) {
    clearInterval(heightTimer)
  }
})

// 暴露方法给父组件
defineExpose({
  reload,
  adjustHeight
})
</script>

<style lang="scss" scoped></style>
